from flask import Blueprint, request
from db import db
from sqlalchemy import desc

from entity.Response import success,error
from entity.Stream import Stream
from entity.User import User

from controller.LoginController import getUsername

from socketIO import socketIO as socketio
from flask_socketio import join_room,leave_room,send
from threading import Lock
SocketThread = None
thread_lock = Lock()

streamController = Blueprint('streamController',__name__)

# 这是一个dict key：房间号 value：这个房间号里有哪些人
roomDict = {}

"""
加入直播间后先和socket建立连接
"""
@socketio.on('connect', namespace='/stream')
def model_connect():
    print('namespace=stream连接成功')
    pass

"""
把同一个直播间的人用socketio加入到一个房间 这样只在这个房间发消息 只有在这个房间的人才能收到
input:
username
roomId
output:
xxxx加入房间
"""
@socketio.on('joinRoom',namespace='/stream')
def joinRoom(data):
    username = data['username']
    roomId = data['roomId']
    join_room(roomId)
    print(username + '加入了' + str(roomId))

    # 加入到这个房间的用户列表中
    if roomId in roomDict:
        roomDict[roomId].append(username)
    else:
        array = [username]
        roomDict[roomId] = array

    socketio.emit('joinRoom','<div style="color: #999999;">' + username + '进入直播间' + '</div>',room=roomId,namespace='/stream')

"""
推出直播间时 把用户从socketio当前room中移除
input:
roomId
output:
none
"""
@socketio.on('leaveRoom',namespace='/stream')
def leaveRoom(data):
    username = data['username']
    roomId = data['roomId']

    # 从这个房间的用户列表中移除
    roomDict[roomId].remove(username)

    leave_room(roomId) 

"""
向同一房间内的人发送消息
input:
username
message
roomId
output:
emit
"""
@socketio.on('sendMessage',namespace='/stream')
def sendMessage(data):
    username = data['username']
    message = data['message']
    roomId = data['roomId']
    socketio.emit('joinRoom','<div style="display: flex;align-items: center;"><div style="display: inline-block;max-width: 8em;white-space: nowrap;word-wrap: normal;overflow: hidden;text-overflow: ellipsis;color: #3c9cfe;">' + username + ': </div>' + message + '</div>',room=roomId,namespace='/stream')

"""
获取房间中的观众列表
"""
@socketio.on('getRoomUserList',namespace='/stream')
def getRoomUserList(data):
    roomId = data['roomId']
    roomUserList = roomDict[roomId]
    dataList = []
    for username in roomUserList:
        user = User.query.filter_by(username=username).first()
        dataList.append(user.to_dict())
    socketio.emit('getRoomUserList',dataList,room=roomId,namespace='/stream')

"""
主播观众互动连麦 后端只是做一个消息转发
input:
username 主播要和谁连麦
roomId
output:
none
"""
@socketio.on('interactiveChat',namespace='/stream')
def interactiveChat(data):
    username = data['username']
    roomId = data['roomId']

    socketio.emit('interactiveChat',username,room=roomId,namespace='/stream')

"""
后端做一个消息转发
input:
username 要发给谁
roomId
message
output:
none
"""
@socketio.on('messageForward',namespace='/stream')
def messageForward(data):
    username = data['username']
    roomId = data['roomId']
    message = data['message']

    socketio.emit('messageForward',{'username': username,'message': message},room=roomId,namespace='/stream')

"""
添加一条直播信息
input:
stream form
output:
none
"""
@streamController.route('/addStreamInfo',methods=['POST'])
def addStreamInfo():
    title = request.get_json().get('title')
    cover = request.get_json().get('cover')
    roomId = request.get_json().get('roomId')

    username = getUsername()

    stream = Stream.query.filter_by(username=username).first()
    if stream != None:
        return error(message='您已创建过一个直播间了')
    
    stream = Stream(username=username,title=title,cover=cover,roomId=roomId)
    db.session.add(stream)
    db.session.commit()

    return success(message='创建直播间成功')

"""
获取所有直播间信息
input:
none
output:
streamList
"""
@streamController.route('/getAllStreamRoom',methods=['GET'])
def getAllStreamRoom():
    streamList = Stream.query.order_by(desc(Stream.status)).order_by(desc(Stream.view)).all()
    dataList = []
    for stream in streamList:
        user = User.query.filter_by(username=stream.username).first()
        dataDict = stream.to_dict()
        dataDict['avatar'] = user.avatar
        dataList.append(dataDict)

    return success(message='获取全部直播成功',data=dataList)

"""
根据用户名获取指定用户直播间
input
username
output:
直播间信息
"""
@streamController.route('/getStreamRoomByUsername',methods=['GET'])
def getStreamRoomByUsername():
    username = getUsername()
    stream = Stream.query.filter_by(username=username).first()
    if stream == None:
        return success(message='当前用户不存在直播间',data=None)
    
    return success(message='获取直播间成功',data=stream.to_dict())

"""
开启/关闭直播间
input:
status username
output:
none
"""
@streamController.route('/updateStreamRoomInfo',methods=['PUT'])
def updateStreamRoomInfo():
    username = getUsername()
    title = request.get_json().get('title')
    cover = request.get_json().get('cover')
    status = request.get_json().get('status')

    stream = Stream.query.filter_by(username=username).first()
    if stream == None:
        return error(message='直播间不存在')
    
    Stream.query.filter_by(username=username).update({'title': title, 'cover': cover,'status': status})
    db.session.commit()

    return success(message='直播间状态更新成功')

"""
更新直播间人数
input:
roomId 房间号
mode 加1还是减1
output:
none
"""
@streamController.route('/updateRoomView',methods=['PUT'])
def updateRoomView():
    roomId = request.args.get('roomId')
    mode = request.args.get('mode')
    mode = int(mode)
    stream = Stream.query.filter_by(room_id=roomId).first()
    if stream == None:
        return error(message='目标直播间不存在')
    
    if mode == 0:
        stream.view = stream.view + 1 
    else:
        if stream.view > 0:
            stream.view = stream.view - 1

    Stream.query.filter_by(room_id=roomId).update({'view': stream.view})
    db.session.commit()

    return success(message='更新直播间人数成功')